package com.archive.forum.service;

import com.archive.forum.dto.ResultDTO;
import com.archive.forum.mapper.*;
import com.archive.forum.model.UserLike;
import com.archive.forum.model.UserLikeExample;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class LikeService {
    @Autowired
    private PostMapper postMapper;
    @Autowired
    private CommentMapper commentMapper;
    @Autowired
    private UserLikeMapper userLikeMapper;
    @Autowired
    private PostExtMapper postExtMapper;
    @Autowired
    private CommentExtMapper commentExtMapper;

    @Transactional
    public ResultDTO like(Integer userId, Integer targetId, Integer type) {
        // 检查是否已经点赞
        UserLikeExample example = new UserLikeExample();
        example.createCriteria()
                .andUserIdEqualTo(userId)
                .andTargetIdEqualTo(targetId)
                .andTypeEqualTo(type);

        boolean isLiked = userLikeMapper.countByExample(example) > 0;

        if (isLiked) {
            // 取消点赞
            userLikeMapper.deleteByExample(example);
            updateLikeCount(targetId, type, -1);
        } else {
            // 点赞
            UserLike userLike = new UserLike();
            userLike.setUserId(userId);
            userLike.setTargetId(targetId);
            userLike.setType(type);
            userLike.setGmtCreate(System.currentTimeMillis());
            userLikeMapper.insert(userLike);

            updateLikeCount(targetId, type, 1);
        }
        return ResultDTO.okOf();
    }

    private void updateLikeCount(Integer targetId, Integer type,int count) {
        if (type == 1) { // 帖子
            postExtMapper.updateLikeCount(targetId, count);
        } else { // 评论
            commentExtMapper.updateLikeCount(targetId,count);
        }
    }

}